import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

/// @date 2020/08/26  17:43
/// @author 程志强
/// @des

class BatteryPluginRoute extends StatefulWidget {
  @override
  _BatteryPluginRouteState createState() => _BatteryPluginRouteState();
}

class _BatteryPluginRouteState extends State<BatteryPluginRoute> {
  static const platform = const MethodChannel('samples.flutter.io/battery');
  String _batteryLevel = 'Unknown battery level.';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("获取电量"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            RaisedButton(
              child: Text("Get Battery Level"),
              onPressed: _getBatteryLevel,
            ),
            Text(_batteryLevel ?? "==")
          ],
        ),
      ),
    );
  }

  Future<Null> _getBatteryLevel() async {
    String batteryLevel;
    try {
      final int result = await platform.invokeMethod("getBatteryLevel");
      batteryLevel = 'Battery level at $result % .';
    } catch (e) {
      batteryLevel = 'Fail to get battery level  ${e.message} .';
    }
    setState(() {
      _batteryLevel = batteryLevel;
    });
  }
}
